import tempfile
# import tkinter as tk
import ttkbootstrap as tk

from ttkbootstrap.utility import enable_high_dpi_awareness
from pathlib import Path
from PIL import Image, ImageTk

from src.log import HOMEP
from src.draw import drawMessageImage
from src.common import FONT_FILE_NAME, shutdown


class Message():
    
    def __init__(self):
        super().__init__()
        
        # 基本属性设置
        self.transparent_color = '#fffffe'
        self.window = None

        self.title = ""
        self.bg_color = "#FFFFFF"
        self.font_color = "#000000"
        self.window_radius = 0
        self.padding = 0
        self.delay = 3000

        # 默认隐藏窗口
        # self.hide()
 
    def initUI(self, params):
        """显示窗口，添加了异常处理以提高稳定性"""
        try:
            self.window = tk.Toplevel()
            self.window.withdraw()
            self.window.overrideredirect(True)
            self.window.attributes('-topmost', True)
            # 启用高清支持
            # setup_hdpi(self.window)

            self.title = params.title
            self.window.title(self.title)
            
            # 根据消息类型设置背景颜色
            if params.type == 'info':
                self.bg_color = "#909399"
                self.font_color = "#ffffff"
            elif params.type == 'primary':
                self.bg_color = "#409eff"
                self.font_color = "#ffffff"
            elif params.type == 'success':
                self.bg_color = "#22c55e"
                self.font_color = "#ffffff"
            elif params.type == 'warning':
                self.bg_color = "#e6a23c"
                self.font_color = "#ffffff"
            elif params.type == 'error':
                self.bg_color = "#f56c6c"
                self.font_color = "#ffffff"
            elif params.type == 'black':
                self.bg_color = "#000000"
                self.font_color = "#ffffff"
            else:
                self.bg_color = "#909399"
                self.font_color = "#ffffff"
            
            # 设置透明色
            try:
                self.transparent_color = '#000001'
                self.window.configure(bg=self.transparent_color)
                self.window.attributes('-transparentcolor', self.transparent_color)
            except Exception:
                pass

            # 加载字体
            font_path = str(HOMEP.joinpath('rawfile', FONT_FILE_NAME))
            with tempfile.TemporaryDirectory() as temp_dir:
                temp_img = Path(temp_dir) / 'message.png'
                # 绘制图像
                has_image = drawMessageImage(font_path, self.bg_color, self.font_color, params.content, str(temp_img))

                if has_image:
                    original_image = Image.open(temp_img)
                    # 缩小
                    original_image = original_image.resize((int(original_image.width * 0.8), int(original_image.height * 0.8)))

                    # Pillow 图像转换为 Tkinter 可用的格式
                    tk_image = ImageTk.PhotoImage(original_image)

                    # 创建并配置 Label 组件来显示图片
                    image_label = tk.Label(self.window, image=tk_image)
                    # 设置 Label 组件的背景颜色为透明
                    image_label.config(background=self.transparent_color)
                    image_label.image = tk_image

                    width = original_image.width + 20
                    height = original_image.height + 20
                else:
                    raise Warning("生成图片失败")

                if params.position == 'top':
                    # 消息显示在距离屏幕顶部80px的地方,水平居中
                    self.window.geometry(f"{width}x{height}+{self.window.winfo_screenwidth() // 2 - width // 2}+80")
                elif params.position == 'bottom':
                    # 消息显示在距离屏幕底部120px的地方,水平居中
                    self.window.geometry(f"{width+20}x{height+20}+{self.window.winfo_screenwidth() // 2 - width // 2}+{self.window.winfo_screenheight() - height - 120}")     
                else:
                    # 消息显示在距离屏幕底部120px的地方,水平居中
                    self.window.geometry(f"{width+20}x{height+20}+{self.window.winfo_screenwidth() // 2 - width // 2}+{self.window.winfo_screenheight() - height - 120}")
                image_label.place(relx=0.5, rely=0.5, relwidth=1, relheight=1, anchor='center')

                # 延迟关闭时间
                self.delay = params.delay
                self.window.after(self.delay, self.close)

        except Exception as e:
            print(f"显示消息错误: {e}")
            import traceback
            traceback.print_exc()
    
    def show(self):
        self.window.deiconify()
    
    def close(self):
        shutdown()


def create(parser):
    parser.add_argument("--title", "-t", type=str, default="消息", help="消息标题")
    parser.add_argument("--position", "-p", type=str, default='top', help="消息位置")
    parser.add_argument("--type", "-y", type=str, default='info', help="消息类型")
    parser.add_argument("--content", "-m", type=str, default='', help="消息内容")
    parser.add_argument("--delay", "-d", type=lambda x: int(x) if x.isdigit() else 3000, default=3000, help="消息显示时间")
    params = parser.parse_args()

    enable_high_dpi_awareness()
    root = tk.Window(alpha=0.0, overrideredirect=True, maxsize=(1, 1))
    message = Message()
    message.initUI(params)
    message.show()
    root.mainloop()
